package com.benyq.networkprogramme.tcp

import android.util.Log
import com.benyq.networkprogramme.base.bean.MsgEvent
import org.greenrobot.eventbus.EventBus
import java.net.ServerSocket
import java.net.Socket
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * @author benyq
 * @date 18-9-24 22:58
 * @E-mail： 1520063035@qq.com
 * @description
 */
class TcpReceiver(serverPort:Int) {

    private lateinit var serverSocket: ServerSocket

    private var executorService : ExecutorService = Executors.newSingleThreadExecutor()


    private val runnableReceiverMsg = Runnable {
        var socket: Socket = serverSocket.accept()
        val inputStream = socket.getInputStream()
        val buffer = ByteArray(10 * 1024)
        var read = -1
//        read = inputStream.read(buffer)
//        Log.e("susan---received", String(buffer,0, read))
        inputStream.use {
            while(it.read(buffer).also { read = it } != -1){
                Log.e("susan---received", String(buffer, 0, read))
                EventBus.getDefault().post(MsgEvent("Susan", String(buffer, 0, read)))
            }
        }
    }

    init {
        initSocket(serverPort)
    }

    private fun initSocket(serverPort: Int){
        serverSocket = ServerSocket(serverPort)
        executorService.execute(runnableReceiverMsg)
//        Thread(runnableReceiverMsg).start()
    }



}